﻿using ArtMath.Resource;
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Globalization;

namespace ArtMath.Converter
{
    public class BooleanConverter : TypeConverterBase
    {
        public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
        {
            return true;
        }
        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            return new StandardValuesCollection(new object[] { true, false });
        }
        public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
        {
            return false;
        }
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            string str = value as string;
            if (str != null)
            {
                return str.Equals(Resources.Translate("Yes"), StringComparison.OrdinalIgnoreCase);
            }
            return base.ConvertFrom(context, culture, value);
        }
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (value != null)
            {
                if (value is bool)
                {
                    if (destinationType == typeof(string))
                    {
                        return (bool)value ? Resources.Translate("Yes") : Resources.Translate("No");
                    }
                    else if (destinationType == typeof(InstanceDescriptor))
                    {
                        return new InstanceDescriptor(typeof(bool).GetConstructor(
                            new Type[] { typeof(string) }),
                            new string[] { value.ToString() });
                    }
                }
                else
                {
                    return value.ToString();
                }
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
}
